import router from '@/router'
import nprogress from 'nprogress'
import api from './axios'

let whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
    let result = await tokenToDate()
    if (result) {
        if (to.path == '/login') {
            ElMessage({
                message: "已登录！",
                type: "warning",
            });
            next(from.path)
        } else {
            next()
        }
    } else {
        if (whiteList.indexOf(to.path) != -1) {
            next()
        } else {
            ElMessage({
                message: "请登录在进入！",
                type: "warning",
            });
            next('/login')
        }
    }
    nprogress.done()

})

router.afterEach((to, from, next) => {
    nprogress.done()
})

//进入使用通过token获取数据
const tokenToDate = async () => {
    const token = localStorage.getItem('token')
    if(token==''|| token == null){
        return false
    }
    try {
        let config = { headers: {"Content-Type":"application/x-www-form-urlencoded"}};
        const data = await api.post("/user/token",{token},config);
        console.log(data)
        sessionStorage.setItem("nickname", data.nickname);
        sessionStorage.setItem("userId", data.id);
        return true
    } catch (error) {
        ElMessage({
            message: "登录已过期，请重新登录！",
            type: "warning",
        });
        sessionStorage.clear()
        localStorage.clear()
    }
    return false
};